package xyz.thoughtset.viewer.modules.ds.http.core.req;

import lombok.AllArgsConstructor;
import lombok.Data;
import okhttp3.OkHttpClient;
import org.springframework.web.util.UriComponentsBuilder;

@Data
@AllArgsConstructor
public abstract class BaseReq {
    protected boolean wasHttp;
    protected String baseUrl;
    protected OkHttpClient okHttpClient;

    protected String buildUrl(String url,boolean formatUrl) {
        String fullUrl;
        if (url == null) {
            if (baseUrl != null) {
                fullUrl = baseUrl;
            } else {
                throw new NullPointerException("在设置 BaseUrl 之前，您必须指定具体路径才能发起请求！");
            }
        } else {
            url = url.trim();
            boolean isFullPath = url.startsWith("https://")
                    || url.startsWith("http://")
                    || url.startsWith("wss://")
                    || url.startsWith("ws://");
            if (isFullPath) {
                fullUrl = url;
            } else if (baseUrl != null) {
                fullUrl = baseUrl + url;
            } else {
                throw new NullPointerException("在设置 BaseUrl 之前，您必须使用全路径URL发起请求，当前URL为：'" + url + "'");
            }
        }
        if (wasHttp && fullUrl.startsWith("http")) {
            fullUrl = fullUrl.replaceFirst("http", "ws");
        }
        if (!wasHttp && fullUrl.startsWith("ws")) {
            fullUrl = fullUrl.replaceFirst("ws", "http");
        }


        if (formatUrl) {
            UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(fullUrl);
            return uriBuilder.toUriString();
        } else {
            return fullUrl;
        }

    }


    public abstract String doGet(String url,boolean formatUrl);
    public abstract String doPost(String url,boolean formatUrl,String jsonStr);

}
